﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Chaunce.Web.Core.Infrastructure.Extensions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using Chaunce.FrameWork.NetCore.Utility.Exceptions;
using Chaunce.FrameWork.NetCore.SysCore.Infrastructure;

namespace Chaunce.Web.Core.Infrastructure
{
    /// <summary>
    ///配置应用程序启动时身份验证中间件
    /// </summary>
    public class AuthenticationStartup : IChaunceStartup
    {
        /// <summary>
        /// 添加 处理身份认证服务相关的中间件实现
        /// </summary>
        /// <param name="services">Collection of service descriptors</param>
        /// <param name="configuration">Configuration root of the application</param>
        public void ConfigureServices(IServiceCollection services, IConfigurationRoot configuration)
        {
            //增加 bearer 认证
            var jwtBearer = services.GetChaunceConfig().JwtBearer;
            if (jwtBearer == null)
            {
                throw new ChaunceException("jwtbearer参数不能为空");
            }
            //启用bearer认证方式
            services.AddAuthorization(auth =>
            {
                auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
                    .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
                    .RequireAuthenticatedUser()
                    .Build());
            });
           
            //添加jwtbearer授权
            services.AddAuthentication()
              .AddJwtBearer(cfg =>
              {
                  cfg.RequireHttpsMetadata = false;
                  cfg.SaveToken = true;

                  cfg.TokenValidationParameters = new TokenValidationParameters()
                  {
                      ValidIssuer = jwtBearer.ValidIssuer,//Token颁发机构                        
                      ValidAudience = jwtBearer.ValidAudience,//颁发给谁
                      IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtBearer.Key)),//密钥          
                  };
              });
        }

        /// <summary>
        /// 添加要使用的中间件
        /// </summary>
        /// <param name="application">Builder for configuring an application's request pipeline</param>
        public void Configure(IApplicationBuilder application)
        {
            application.UseAuthentication();
        }

        /// <summary>
        /// Gets order of this startup configuration implementation
        /// </summary>
        public int Order
        {
            //authentication should be loaded before MVC
            get { return 500; }
        }
    }
}
